import jwt
import datetime
from django.conf import settings

class ToolJWT:
    # 生成token
    # user为一个字典，
    def __init__(self):
        self.header = {
            "alg": "HS256",
            "typ": "JWT"
        }
        self.SECRET_KEY = settings.SECRET_KEY


    def get_token(self,user):
        set_time = datetime.datetime.now() + datetime.timedelta(days=2)
        payload = {
            'userid': user.get('userid'),
            'username':user.get('username'),#用户名
            'exp':set_time.timestamp()#设置过期时间
        }
        print(payload.get('exp'))
        return jwt.encode(payload=payload,key=self.SECRET_KEY,algorithm='HS256',headers=self.header)
    # 验证token

    def check_token(self,token):
        try:
            res = jwt.decode(jwt=token, key=self.SECRET_KEY, algorithms=['HS256'],headers=self.header)
            print(res)
            return res
        except jwt.ExpiredSignatureError: # 验证token是否过期
            raise Exception('token已失效')
        except jwt.InvalidTokenError:  # 验证token是否有效
            raise Exception('token无效')


# user = {'id':1,'username':'张三'}
# a = ToolJWT()
# print(a.get_token(user))
# print(a.check_token("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjEsInVzZXJuYW1lIjoibm4iLCJleHAiOjE3MzIwNDg1NDJ9.6z1Inx2JIQHmYc0xjNkN7uU_XL8m7P0Lm-bNk9jgKmM"))
